<template>
  <div style="position:relative;">
    <input
      v-model="keyword"
      @focus="showList = true"
      @blur="hideList"
      @input="onInput"
      placeholder="请输入城市名"
    />
    <ul
      v-if="showList && filteredCities.length"
      style="position:absolute;top:100%;left:0;z-index:10;background:#fff;border:1px solid #ddd;width:100%;margin:0;padding:0;list-style:none;"
    >
      <li v-for="city in filteredCities" :key="city" @mousedown.prevent="select(city)" style="padding:4px 8px;cursor:pointer;">
        {{ city }}
      </li>
    </ul>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { cities } from './cities.js'

const keyword = ref('')
const showList = ref(false)

const filteredCities = computed(() =>
  keyword.value
    ? cities.filter(city => city.includes(keyword.value))
    : []
)

function onInput() {
  showList.value = !!keyword.value
}

function select(city) {
  keyword.value = city
  showList.value = false
}

function hideList() {
  // 延迟隐藏，为了保证点击下拉项还能被选中
  setTimeout(() => (showList.value = false), 150)
}
</script>